<template>
  <div class="app-container">
    <el-row>

<!--扫码界面 -->
      <div >
        <el-card>
          <div slot="header" class="clearfix">
            <span>扫码登记信息</span>

            <el-button style="float: right; padding: 3px 0" type="text">选择所在城市后，获取二维码</el-button>
          </div>
          <div class="image-container">
            <img  ref="vcImg" style="width: 200px;height: 200px" :src="url"/>
          </div>
          <el-form :model="queryParams" style="margin-top: 10px" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="50px">
            <el-form-item label="省份" prop="province">
              <el-select v-model="queryParams.province" placeholder="请选择" clearable @change="getCityList(queryParams.province)">
                <el-option
                  v-for="dict in provinceList"
                  :key="dict.id"
                  :label="dict.province"
                  :value="dict.code"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="城市" prop="city" >
              <el-select v-model="queryParams.city" placeholder="选择省份后选择城市" clearable size="small" filterable>
                <el-option
                  v-for="dict in cityList"
                  :key="dict.cityCode"
                  :label="dict.city"
                  :value="dict.cityCode"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div style="padding: 14px;">
            <span>当前状态:{{loginStatus}}</span>
            <div class="bottom clearfix">
              <el-button type="text" class="button" @click="getLoginORCode">刷新二维码</el-button>
            </div>
          </div>
          <div>

          </div>
        </el-card>
      </div>
    </el-row>
    <el-card>
      <div slot="header" class="clearfix">
        <span>用户信息</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="updateOrderLoginStatus">检测信息是否正常</el-button>
      </div>
      <el-button type="primary" v-clipboard:copy="userCookie" v-clipboard:success="onCopySuccess" v-clipboard:error="onCopyError">复制登陆信息</el-button>
    </el-card>
  </div>
</template>

<script>
import { addAdminOrder, listOrder, updateOrderLoginStatus } from '@/api/mx/order'
import axios from 'axios'
import { cityList, listProvince } from '@/api/cityManagement'

export default {
  name: "hello",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // mx订单表格数据
      orderList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        goodsName: null,
        presetTime: null,
        jdAccount: null,
        cookie: null,
        cookieRecordTime: null,
        fishAccount: null,
        customerName: null,
        address: null,
        phoneNumber: null,
        mxType: null,
        status: null,
        createUserId: null,
        province: null,
        goodsNowPrice: null,
        goodsAmount: null,
        orderPrice: null,
        cashback: null,
        realIncome: null,
        resCookie: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: '下单时间不能为空', trigger: 'blur' }
        ]
      },
      /************************************ 登陆**************************************/
      url: null,//登陆二维码
      loginInfo: null,//轮询扫码响应的信息
      QRCodeKey: null,
      wlfstk_smdl: null,//登陆参数
      loginStatus: null,//登陆情况
      userCookie: null,//用户的cookie
      provinceList: [],//省份列表

      cityList:[],//城市列表
      proxx:null,//请求二维码时候返回的结果，轮询时候需要调用
    }
  },
  created() {
    this.getList();
    this.getProvince();
    //this.getLoginInfo()
  },
  methods: {
    /** 查询mx订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取城市信息
    getProvince(){
      listProvince().then(res=>{
        if (res.code === 200) {
          this.provinceList = res.data
          this.getLoginInfo()

        }
      })
    },
    getCityList(code){

      if (code === null) {
        return
      }
      let obj={}
      obj = this.provinceList.find((item) => { // 这里的provincelist就是上面省的数据
        return item.code === code // 筛选出匹配数据，这里的id是接口数据中的每一项的id
      })
      let data={
        provinceId : obj.id
      }
      //获取城市列表
      cityList(data).then(res=>{
        if (res.code === 200) {
          this.cityList = res.data
        }

      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsName: null,
        presetTime: null,
        jdAccount: null,
        cookie: null,
        cookieRecordTime: null,
        createTime: null,
        fishAccount: null,
        customerName: null,

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加mx订单";
    },
    /** 修改按钮操作 */


    /** 导出按钮操作 */
    handleExport() {
      this.download('jd/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    /**获取京东登陆二维码**/

    getLoginORCode() {
      if (this.queryParams.province === null || this.queryParams.province === undefined) {
        this.$message.error('请选择省份')
        return;
      }else if (this.queryParams.city === null || this.queryParams.city === undefined) {
        this.$message.error('请选择城市')
        return
      } else {
        axios.post('/py/getQRcode', this.queryParams).then(response => {
          //const blob = new Blob([response.data], { type: response.headers['content-type'] }); // 创建Blob对象
          //saveAs(blob, 'image.jpg'); // 调用saveAs方法保存文件到本地
          if (response.status === 200) {

            this.url = "data:image/png;base64," +response.data.qrcode

            this.QRCodeKey=response.data.cookies
            this.wlfstk_smdl=response.data.wlfstk_smdl;
            this.proxx=response.data.proxx;
            this.getLoginResult()

          }

        })
          .catch(error => {
            console.log(error);
          });
      }



    },
    //获取登陆结果
    getLoginResult() {
      let data={
        'wlfstk_smdl': this.wlfstk_smdl+'', 'cookies': this.QRCodeKey+'','proxx':this.proxx
      }
      axios.defaults.headers.common['Content-Type'] = 'application/json';
      this.pollingTimer = setInterval(() => {
        axios.post('/py/getresult', data).then(res => {
          console.log(res)
          this.loginStatus = res.data.msg
          this.userCookie=res.data.qrcookies
          if (res.data.code === 200) {
            clearInterval(this.pollingTimer) // 停止轮询
            console.log('请求成功，停止轮询')
            //将用户信息存入数据库中
            let data={
              cookie: this.userCookie,
              activeName: this.queryParams.activeName,
              createUserId: this.queryParams.createUserId
            }
            addAdminOrder(data).then(res=>{
              if (res.code === 200) {
                this.$message.success('获取成功')
                //this.getList();
              }
            })
          }else if (res.data.code === 500) {
            clearInterval(this.pollingTimer) // 停止轮询
            this.loginStatus = '获取失败，请选择您当前所在地区';
            this.$message.error("获取失败，请选择您当前所在地区")
          }
        })
          .catch(error => {
            console.error(error)
          })
      }, 3000) // 每3秒执行一次请求
    },

    beforeDestroy() {
      clearInterval(this.pollingTimer) // 组件销毁前清除定时器
    },
    onCopySuccess(){
      this.$message.success('复制成功')
    },
    onCopyError(){
      this.$message.error('复制失败')
    },
    /**
     * 查看我的订单
     */
    viewMyOrder(){
      this.$router.push('/index');
    },
    /**
     * 从链接中获取信息
     */
    getLoginInfo() {
      let province = this.$route.query.province
      let city = this.$route.query.city
      let createUserId = this.$route.query.createUserId
      let activeName = this.$route.query.activeName
      console.log(province !== 'undefined' && province !== '')
      if (province !== 'undefined' && province !== '') {
        this.queryParams.province = province
        this.getCityList(province)
        if (city !== 'undefined'&&city !== '') {
          this.queryParams.city = city
        }
      }

      if (createUserId !== 'undefined'&& createUserId !== '') {
        this.queryParams.createUserId = createUserId
      }
      this.queryParams.activeName = activeName
      this.getLoginORCode()
      console.log(this.queryParams)
    },


    /**
     * 获取最新登陆状态
     * @param row
     */
    updateOrderLoginStatus(row){
      if (!this.userCookie) {
        this.$message.error('未获取到信息，请选择正确当前所在地区后获取二维码');
        return
      }
      let data={
        cookie: this.userCookie
      }
      updateOrderLoginStatus(data).then(response => {
        if (response.code === 200) {
          this.$message.success("信息正常")
          this.getList();
        }
      });
    },
  }
};
</script>

<style>
.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  /* 如果希望图片垂直居中整个视口，可以使用这行代码 */
}

</style>
